﻿using IBll;
using IBll.DTO;
using IDal;
using Model;

namespace Bll
{
    public class StudentBll : IStudentBll
    {
        public StudentBll(IBase<Student> db)
        {
            Db = db;
        }

        public IBase<Student> Db { get; }

        public async Task<int> AddAsync(Student t)
        {
            return await Db.AddAsync(t);
        }

        public async Task<int> DeleteAsync(int id)
        {
            return await  Db.DeleteAsync(id);
        }

        public IQueryable<Student> GetAll()
        {
            return Db.GetAll();
        }

        public Student GetSingle(int id)
        {
            return Db.GetSingle(id);
        }

        public PageResultDTo<Student> GetStudentPage(int index, int size, string? name)
        {
            //预备查，拼接条件，取总数，分页查
            var values=Db.GetAll();
            if (!string.IsNullOrEmpty(name))
            {
                values = values.Where(x => x.name.Contains(name));
            }
            var c = values.Count();
            var data = values.OrderBy(x => x.id).Skip((index - 1) * size).Take(size).ToList();
            PageResultDTo<Student> dto = new PageResultDTo<Student>();
            dto.data = data;
            dto.count = c;
            return dto;
        }

        public async Task<int> RangeDeleteAsync(string idsting)
        {
            //先插再删
            //id="1,2,3,4" 把字符串转为数组集合
            int[] idlist=idsting.Split(',').Select(d=>Convert.ToInt32(d)).ToArray();
            var list = Db.GetAll().Where(x => idlist.Contains(x.id));
            return await Db.RangeDeleteAsync(list);
        }

        public async Task<int> UpdateAsync(Student t)
        {
            return await Db.UpdateAsync(t);
        }
    }
}
